﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using Biz.EF;
using Biz.Properties;
using log4net;
using Oracle.ManagedDataAccess.Client;

namespace Biz.Process
{
    public class BizFacade
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(BizFacade));
        /// <summary>
        /// 根据企业排口表中在线编码从中间库取对应数据,注意数据要将Envi_PS_Waste_Water中累加流量加上中间库中小时流量；
        /// 借用我司排口表字段Let_Port_Whereabouts存放时间标志
        /// </summary>
        public static void SynFromHacToTinz()
        {
            try
            {
                var formatSrc = new DateTimeFormatInfo { ShortDatePattern = "yyyy/M/d H:mm:ss" };
                //var formatTar = new DateTimeFormatInfo { ShortDatePattern = "yyyy-MM-dd HH:mm:ss" };
                using (var oracleConnection = new OracleConnection(Settings.Default.OracleConnectionString))
                using (var ctx = new TinzContext())
                using (var ctx4Base = new TinzContext())
                {
                    var portMapsInTinz = ctx4Base.Envi_PS_Waste_Water_Let_Port.ToList();
                    oracleConnection.Open();
                    foreach (var map in portMapsInTinz)
                    {
                        try
                        {
                            var waterFlow =
                                ctx.Envi_PS_Waste_Water_Flow.FirstOrDefault(
                                    t =>
                                        t.Pollution_Source_ID != null &&
                                        t.Pollution_Source_ID == map.Pollution_Source_Id);
                            decimal total = 0;
                            if (waterFlow!=null&&waterFlow.Total_Flow != null)
                            {
                                total = waterFlow.Total_Flow.Value;
                            }
                            if (string.IsNullOrEmpty(map.online_inspect_Number)) continue;

                            if (map.Pollution_Source_Id == null) continue;

                            if (string.IsNullOrEmpty(map.Let_Port_Whereabouts))
                                map.Let_Port_Whereabouts = "2018-07-01 00:00:00";

                            //var cmdText = "select * from hac_emos2.ps_water_hour_data  where monitortime > TO_DATE('" +
                            //              map.Let_Port_Whereabouts + "', 'YYYY-MM-DD HH24:MI:SS') and outputcode='" +
                            //              map.online_inspect_Number + "' order by monitortime";
                            var cmdText = "select * from ps_water_hour_data  where monitortime > TO_DATE('" +
                                          map.Let_Port_Whereabouts + "', 'YYYY-MM-DD HH24:MI:SS') and outputcode='" +
                                          map.online_inspect_Number + "' order by monitortime";
                            Log.Info(cmdText);
                            using (OracleCommand cmd = new OracleCommand(cmdText, oracleConnection))
                            {
                                cmd.CommandType = CommandType.Text;
                                OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                                DataSet dataSet = new DataSet();
                                adapter.Fill(dataSet); //执行cmd.ExecuteReader();并将结果添加到DataSet容器中
                                Log.Info("PsId:" + map.Pollution_Source_Id + "\t" + map.Pollution_Source_Name);


                                if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                                {
                                    Log.Info("Records number:" + dataSet.Tables[0].Rows.Count);
                                    foreach (DataRow row in dataSet.Tables[0].Rows)
                                    {
                                        try
                                        {
                                            var monitorTimeStr = row["MONITORTIME"].ToString();
                                            Log.Debug("MONITORTIME String:" + monitorTimeStr);
                                            var timeTag = Convert.ToDateTime(monitorTimeStr, formatSrc);
                                            map.Let_Port_Whereabouts = monitorTimeStr;
                                            var item = new Envi_UploadDataOnline();
                                            item.PS_NUM = map.online_inspect_Number;
                                            item.Monitor_Time = timeTag;
                                            try
                                            {
                                                item.Instant_Flow = row["AVGFLOW"] == null
                                                    ? 0
                                                    : decimal.Parse(row["AVGFLOW"].ToString());
                                            }
                                            catch (Exception ex)
                                            {
                                                Log.Error(ex.Message);
                                                Log.Error(row["AVGFLOW"]);
                                            }

                                            try
                                            {
                                                item.COD = row["COD"] == null
                                                    ? 0
                                                    : decimal.Parse(row["COD"].ToString());
                                            }
                                            catch (Exception ex)
                                            {
                                                Log.Error(ex.Message);
                                                Log.Error(row["COD"]);
                                            }

                                            try
                                            {
                                                item.PH = row["PH"] == null ? 0 : decimal.Parse(row["PH"].ToString());
                                            }
                                            catch (Exception ex)
                                            {
                                                Log.Error(ex.Message);
                                                Log.Error(row["PH"]);
                                            }

                                            item.FunctionNo = "2411";
                                            item.UpLoadTime = DateTime.Now;

                                            if (item.Instant_Flow != null)
                                            {
                                                total += item.Instant_Flow.Value;
                                            }

                                            item.Total_Flow = total;
                                            Log.Info("Total:" + total);
                                            ctx.Envi_UploadDataOnline.Add(item);
                                            ctx.SaveChanges();
                                            var otherItem = new Envi_UploadDataOnline()
                                            {
                                                PS_NUM = item.PS_NUM,
                                                Monitor_Time = item.Monitor_Time,
                                                Instant_Flow = item.Instant_Flow,
                                                COD = item.COD,
                                                PH = item.PH,
                                                FunctionNo = "2401",
                                                UpLoadTime = DateTime.Now,
                                                Total_Flow = total
                                            };

                                            ctx.Envi_UploadDataOnline.Add(otherItem);
                                            ctx.SaveChanges();

                                        }
                                        catch (Exception ex)
                                        {
                                            Log.Error(ex);
                                        }
                                    }
                                }

                                ctx4Base.SaveChanges();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }


    }
}
